package org.springframework.samples.mvc.fileupload;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.springframework.samples.mvc.service.ImageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/fileuploadForAjax2")
public class FileUploadForAjax2Controller {

	private static final String template = "file info: %s(id) %s(name) %s(type) %s(size)";
	private final AtomicLong counter = new AtomicLong();

	@Autowired
	private ServletContext servletContext;

	/*
	 * ImageView는 파일 시스템에 있는 이미지 파일을 응답으로 돌려주는 역할을 합니다. 뒷 부분에서 ImageView 클래스를
	 * 작성하게 됩니다.
	 */
	@Resource(name = "imageView")
	ImageView imageView;

	@Autowired
	ImageService imageService;

	@ModelAttribute
	public void ajaxAttribute(WebRequest request, Model model) {
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	}

	@RequestMapping(method = RequestMethod.GET)
	public void fileUploadForm() {
		System.out.println("★★★★★ step 1");

		String rootPath = System.getProperty("catalina.home");
		System.out.println("rootPath=======" + rootPath);

	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody Files processUpload(
			@RequestParam("files[]") MultipartFile[] files, Model model,
			HttpServletRequest request

	) throws IOException, InterruptedException {

		
		
		
		
		System.out.println("★★★★★ step Ajax Ajax");

		String appPath = request.getServletContext().getRealPath("");
		System.out.println("★★★★★appPath=======" + appPath);

		String rootPath = System.getProperty("catalina.home");
		System.out.println("rootPath=======" + rootPath);

		HttpSession session = request.getSession(true);
		ServletContext sc = request.getSession().getServletContext();
		System.out.println("★★★★★===" + System.getProperty("os.name"));
		String osName = System.getProperty("os.name");

		SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = simpledateformat.format(new Date());

		String usrUploadDir = "upload" + File.separator + yyyyMMdd;
		// System.out.println("★★★★★ usrUploadDir="+usrUploadDir);
		// SAVE PATH
		// String filePath = servletContext.getRealPath(File.separator )+
		// usrUploadDir+File.separator ;

		String filePath = "";
		if (!osName.startsWith("Windows")) {
			filePath = "/var/www/html" + File.separator + usrUploadDir
					+ File.separator;
		} else {
			// filePath =
			// "C:\\Development\\workspace-sts-3.6.0.RELEASE\\spring-mvc-showcase\\src\\main\\webapp\\resources"+File.separator+usrUploadDir
			// +File.separator;

			/**
			 * 로컬 아파치 Alias 로 파일 접근 하도록 설정 httpd.conf
			 * 
			 * Alias /upload "C:/Development/upload"
			 * 
			 * <Directory "C:/Development"> AllowOverride None Options None
			 * Order allow,deny Allow from all </Directory>
			 */

			filePath = "C:\\Development" + File.separator + usrUploadDir
					+ File.separator;
		}
		System.out.println("★★★★★ filePath=" + filePath);

		// HttpSession session = request.getSession(true);

		ArrayList<String> uploadedFileNames = new ArrayList<String>();
		ArrayList<ImageFile2> imageFiles2 = new ArrayList<ImageFile2>();
		for (MultipartFile file2 : files) {
			// TODO get file info
			boolean isEmpty = file2.isEmpty();
			String inputName = file2.getName();
			String name=file2.getOriginalFilename();
			String type= file2.getContentType();
			long size= file2.getSize();
			byte[] content = file2.getBytes();
			String url="http://127.0.0.1:5350/upload/"+yyyyMMdd+"/"+name;
			String thumbnailUrl="http://127.0.0.1:5350/upload/"+yyyyMMdd+"/thumbnail/"+name;
			String deleteUrl=url+"?delete=true";
			String deleteType="DELETE";
			long seq = counter.incrementAndGet();
			
			if ("".equalsIgnoreCase(name) && size == 0) {

			} else {

//				String seq = String.valueOf(counter.incrementAndGet());

				String contentType = file2.getContentType();
				file2.getInputStream();
				
				imageFiles2.add(new ImageFile2(seq,url,name,thumbnailUrl,type,size,deleteUrl,deleteType));

				// TODO FILE SAVE
				File newFile = new File(filePath + name);
				// 디렉토리가 없을 경우 생성
				// System.out.println("★★★★★ request.getRealPath(File.separator)="+request.getServletContext().getRealPath(File.separator)
				// );
				if (!newFile.exists()) {
					newFile.mkdirs();
				}

				// String genId = UUID.randomUUID().toString();
				// System.out.println("★★★★ 같은 이름이 존재할경우 genId =="+genId);
				// 같은 이름이 존재할경우는 어떻게 처리하지? UUID 사용해서 처리해야 하는지?
				file2.transferTo(newFile);

				if (!osName.startsWith("Windows")) {
					String folder = filePath;
					String cmd = "chmod 777 -R " + folder;
					Runtime rt = Runtime.getRuntime();
					Process p = rt.exec(cmd);
					p.waitFor();
				}

				uploadedFileNames.add(name);
			}

		} // for end..

		String listString = "";

		for (String s : uploadedFileNames) {
			listString += s + "\t";
		}
		System.out.println("★★★★uploadedFileNames=" + listString);

		if (uploadedFileNames.size() == 0) {

			model.addAttribute("message", "File not found!!! ");
		} else {

			// model.addAttribute("message", "File '" + uploadedFileNames.size()
			// +
			// "' uploaded successfully (uploadedFileNames :"+listString+"---");
			model.addAttribute("message", "File '" + uploadedFileNames.size()
					+ "' uploaded successfully (uploadedFileNames :"
					+ uploadedFileNames.toString() + "---");
			model.addAttribute("uploadedFileNames", uploadedFileNames);

			// 아파치 이미지 링크 주소 가 "/"이걸로 나와야 하므로
			model.addAttribute("usrUploadDir", usrUploadDir.replace("\\", "/"));
			model.addAttribute("osName", osName);
		}

		Files files2 = new Files();
		files2.setFiles(imageFiles2);
		
		return files2;
	}

}
